package com.github.chirspan.xaas.core.util;

import cn.hutool.core.collection.CollectionUtil;
import com.github.chirspan.xaas.core.constant.SecurityConstants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * *******description*******
 * <p>
 * *************************
 *
 * @author chenpan
 * @date 2020/6/3 09:45
 */
public class HeaderSecurityUtils {

    private static HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (Exception e) {
            return null;
        }

    }

    private static String getHeader(String headerName) {
        HttpServletRequest request = getHttpServletRequest();
        if (request != null) {
            return request.getHeader(headerName);
        }

        return null;
    }

    public static String getUserName() {
        return getHeader(SecurityConstants.USER_HEADER);
    }

    public static String getUserId() {
        return getHeader(SecurityConstants.USER_ID_HEADER);
    }

    public static boolean hasRole(String role) {
        Set<String> auths = getUserAuth();
        return CollectionUtil.contains(auths, role);
    }

    public static String getClient() {
        return getHeader(SecurityConstants.CLIENT_HEADER);
    }

    public static Set<String> getUserAuth() {
        String auth = getHeader(SecurityConstants.ROLE_HEADER);
        if (auth != null) {
            return new HashSet<>(Arrays.asList(auth.split(",")));
        }
        return null;
    }
}
